//
//  HMStatusListViewModel.swift
//  WeiBoXR
//
//  Created by acer on 16/9/24.
//  Copyright © 2016年 acer. All rights reserved.
//

import UIKit
import SDWebImage
class HMStatusListViewModel: NSObject {
    lazy var statusList: [HMHomeCellViewModel] = [HMHomeCellViewModel]()
    func loadData(isPullUP: Bool ,callBack: @escaping (Bool,String) -> ()) {
        let accesstoken: String = HMUserAccountViewModel.sharedUserAccountViewModel.accessToken!
        //  获取上拉加载请求需要的微博id
        var maxId: Int64 = 0
        //  获取下拉属性请求需要的微博id
        var sinceId: Int64 = 0

        if isPullUP {
            maxId = statusList.last?.statusModel?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        } else {
            //下拉刷新
            sinceId = statusList.first?.statusModel?.id ?? 0
            
        }
            

        var message: String = "没有加载到最新微博数据"

        HMNetworkTools.sharedTools.requestStatus(accessToken: accesstoken , maxId: maxId , sinceId: sinceId) { (response, error) in
            
            if error != nil {
                print("有错误\(error)")
                callBack(false,message)
                return
            }
            guard let dic = response as? [String: Any] else {
                print("字典格式不正确1")
                callBack(false,message)
                return
            }
            guard let statusArray = dic["statuses"] as? [[String: Any]] else {
                print("字典格式不正确2")
                callBack(false,message)
                return
            }
            //            var tempArr = [HMStatusModel]()
            //            for statusDic in statusArray
            //            {
            //                let statusModel = HMStatusModel(dic: statusDic)
            //                tempArr.append(statusModel)
            //            }
            //            self.statusList = tempArr
            let statusArr = NSArray.yy_modelArray(with: HMStatusModel.self, json: statusArray) as! [HMStatusModel]
            
            var tempArray = [HMHomeCellViewModel]()
            
            let group = DispatchGroup()
            //  遍历模型数组
            for status in statusArr {
                let viewModel = HMHomeCellViewModel(statusModel: status)
                //viewModel.status = status
                tempArray.append(viewModel)
                
                if status.pic_urls?.count == 1 {
                    if let urlString = status.pic_urls?.first?.thumbnail_pic {
                        group.enter()
                        SDWebImageManager.shared().downloadImage(with: URL(string: urlString), options: [], progress: nil, completed: { (image, error, _, _, url) in
//                            print("\(#function)1")
                            group.leave()
                        })
                    }
                }
                if status.retweeted_status?.pic_urls?.count == 1 {
                    
                    if let urlString = status.retweeted_status?.pic_urls?.first?.thumbnail_pic {
                        group.enter()
                        SDWebImageManager.shared().downloadImage(with: URL(string: urlString), options: [], progress: nil, completed: { (image, error, _, _, url) in
//                            print("\(#function)2")
                            group.leave()
                        })
                    }
                }
                //  判断服务器返回的数据个数是否大于0
                if tempArray.count > 0 {
                    message = "加载了\(tempArray.count)条微博数据"
                }

            }
            //  给数据源赋值
//            self.statusList = tempArray
            if isPullUP {
                self.statusList.append(contentsOf: tempArray)
            } else {
                self.statusList.insert(contentsOf: tempArray, at: 0)
            }
            group.notify(queue: DispatchQueue.main, execute: {
//                print("\(#function)3")
                callBack(true,message)
            })
        
        }
    }

}
